<?php
namespace translate\mip;

use translate\translate;
use phpQuery;

class mipTranslate extends translate {

    function getRules(){
        return [
            [$this,'firstRule'],
            [$this,'htmlRule'],
            [$this,'linkRule'],
            [$this,'formSearchRule'],
            [$this,"srcReplace"],
            [$this,'imgRule'],
            [$this,'swiperRule'],
            [$this,'tagReplaceRule'],
            [$this,'seriptReplaceRule'],
            [$this,"removeGetClick"]
        ];
    }

    /**
     * 清理<标签后面的空格
     * @param $content
     * @return mixed
     */
    function firstRule($content){
       $content = preg_replace("|<\s+|","<",$content);
       return $content;
    }

    /**
     * 为html标签加上mid
     * @param $content
     * @return mixed
     */
    function htmlRule($content){
        return str_replace("<html","<html mip",$content);
    }

    /**
     * 加入mip的link样式
     * @param $content
     * @return String
     */
    function linkRule($content){
        $doc =phpQuery::newDocumentHTML($content);
        pq('head')->append('<link rel="stylesheet" type="text/css" href="https://mipcache.bdstatic.com/static/v1/mip.css" >');
        return $doc->htmlOuter();
    }

    /**
     * pcsoft搜索替换规则
     * @param $content
     * @return mixed
     */
    function formSearchRule($content){
        $doc =phpQuery::newDocumentHTML($content);

        if(($mHtmls = pq('form.search-software')) && ($mHtmls->size() > 0)){

            foreach($mHtmls as $key=> $mHtml){
                $htmlObject = pq($mHtml);
                $mHtmlContent = $htmlObject->htmlOuter();

                $attrs = $htmlObject->attr("*");
                $url = $htmlObject->attr("action");
                $method = $htmlObject->attr("method");
                $attrs['url'] = $url;
                $attrs['method'] = $method;

                //
                $mipNode = pq("<mip-form></mip-form>");
                foreach($attrs as $attrName=> $attrValue){
                    if(!empty($attrValue)){
                        $mipNode->attr($attrName,$attrValue);
                    }
                }
                $mipNode->html(pq($mHtml)->html());


                /*$mipNode = "<mip-form url='".$url."' method='".$method."'>".pq($mHtml)->html()."</mip-form>";*/
                $content = str_replace($mHtmlContent,$mipNode,$content);
            }

            return  $content;
        }
        return $doc->htmlOuter();
    }

    /**
     * 图片替换规则
     * @param $content
     * @return mixed
     */
    function imgRule($content){
        return str_replace("<img","<mip-img",$content);
    }

    /**
     * A标签的href中必须包含有http或者https
     * @param $content
     * @return mixed
     */
    /*function aRule($content){
        $doc =phpQuery::newDocumentHTML($content);
        $aS  = pq("a");
        foreach($aS as $a){
            if($href = $a->getAttribute("href")){
                if(preg_match("/^\/\//",$href,$matches)){
                    echo 123;
                }
                var_dump($matches);
            }
        }
        exit;
        return $content;
    }*/

    /**
     * swiper图片滑动转换
     * @param $content
     * @return mixed
     */
    function swiperRule($content){
        $doc =phpQuery::newDocumentHTML($content);
        if(($swiperNodes = pq('.swiper-container')) && ( $swiperNodes->size() > 0 ) ){
            $i = 0;

            if(($temp  = pq(".swiper-button-prev")) && ($temp->size() > 0) ){
                $temp->remove();
            }
            if(($temp  = pq(".swiper-button-next")) && ($temp->size() > 0) ){
                $temp->remove();
            }

            foreach($swiperNodes as $swiperNode){

                if(!$defer = $swiperNode->getAttribute("data-defer")){
                    $defer = 1000;
                }
                if(!$width = $swiperNode->getAttribute("data-width")){
                    $width = 200;
                }
                if(!$height = $swiperNode->getAttribute("data-height")){
                    $height = 100;
                }
                
                $items = [];
                if(($swiperSlides = pq(".swiper-slide",$swiperNode)) && ( $swiperSlides->size() > 0 ) ){
                   foreach($swiperSlides as $swiperSlide){
                       $hrefNode = $this->findFirstElement(pq("a",$swiperSlide));
                       $imgNode =  $this->findFirstElement(pq("mip-img",$swiperSlide));
                       if($imgNode){
                           $href =  '';
                           if($hrefNode){
                               $href =  $hrefNode->getAttribute("href");
                           }
                           $img =   $imgNode->getAttribute("src");
                           $items[] =[$img,$href];
                       }
                   }

                    //
                    $MipDom = phpQuery::newDocumentHTML('<mip-carousel autoplay defer="'.$defer.'" layout="responsive" width="'.$width.'" height="'.$height.'" indicator>');
                    foreach($items as $item){
                        $html = "<mip-img  src='{$item[0]}'></mip-img>";
                        if(!empty($item[1])){
                            $html = "<a target='_blank' href='{$item[0]}'>".$html."</mip-img></a>";
                        }
                        $MipDom->find("mip-carousel")->append($html);
                    }

                    $current = $doc->find(".swiper-container:first");
                    $current->replaceWith($MipDom);
                }
                $i++;
            }

            return $doc->htmlOuter();
        }
        return $content;
    }

    /**
     * 硬关系标签替换
     * @param $content
     */
    function tagReplaceRule($content){
         $doc = phpQuery::newDocumentHTML($content);

         if(($mHtmls = pq('.mip-huajun-downtag')) && ($mHtmls->size() > 0)){
             foreach($mHtmls as $key=> $mHtml){
                 $mHtmlContent = pq($mHtml)->html();
                 $doc->find(".mip-huajun-downtag:eq(".$key.")")->replaceWith("<mip-huajun-downtag>$mHtmlContent</mip-huajun-downtag>");
             }
         }

        if(($mHtmls = pq('.mip-down-hideshow')) && ($mHtmls->size() > 0)){
            foreach($mHtmls as $key=> $mHtml){
                $mHtmlContent = pq($mHtml)->html();
                $doc->find(".mip-down-hideshow:eq(".$key.")")->replaceWith("<mip-down-hideshow hsId='2'>$mHtmlContent</mip-down-hideshow>");
            }
        }

        if(($mHtmls = pq('.mip-365xiazai-header')) && ($mHtmls->size() > 0)){
            foreach($mHtmls as $key=> $mHtml){
                $mHtmlContent = pq($mHtml)->html();
                $doc->find(".mip-365xiazai-header:eq(".$key.")")->replaceWith("<mip-365xiazai-header>$mHtmlContent</mip-365xiazai-header>");
            }
        }

        if(($mHtmls = pq('.mip-365xiazai-tabtap')) && ($mHtmls->size() > 0)){
            foreach($mHtmls as $key=> $mHtml){
                $mHtmlContent = pq($mHtml)->html();
                $doc->find(".mip-365xiazai-tabtap:eq(".$key.")")->replaceWith("<mip-365xiazai-tabtap>$mHtmlContent</mip-365xiazai-tabtap>");
            }
        }

        if(($mHtmls = pq('.mip-vd-tabs')) && ($mHtmls->size() > 0)){
            foreach($mHtmls as $key=> $mHtml){
                $mHtmlContent = pq($mHtml)->html();
                $doc->find(".mip-vd-tabs:eq(".$key.")")->replaceWith("<mip-vd-tabs allow-scroll>$mHtmlContent</mip-vd-tabs>");
            }
        }

        return $doc->htmlOuter();
    }

    /**
     * 标签替换
     * @param $content
     * @return
     */
    function seriptReplaceRule($content){
        $doc = phpQuery::newDocumentHTML($content);
        $doc->find("script")->remove();
        $doc->find("body")->append('<script src="https://mipcache.bdstatic.com/static/v1/mip.js"></script>');
        $jsList = $this->getRuleConfig(__FUNCTION__);

        if($jsList){
            foreach($jsList as $list){
                $doc->find("body")->append('<script src="'.$list.'"></script>');
            }
        }

        //加上token
        $token = $this->getConfig("token");
        $doc->find("body")->append('<mip-stats-baidu token="'.$token.'"></mip-stats-baidu>');

        return $doc->htmlOuter();
    }

    /**
     * 域名替换
     * @param $content
     * @return mixed
     */
    function srcReplace($content){
        return str_replace($this->getConfig("sourceDomain"),$this->getConfig("mipDomain"),$content);
    }

    /**
     * @param $content
     */
    function removeGetClick($content){
        $doc = phpQuery::newDocumentHTML($content);

         if(($mHtmls = pq("script",pq(".get-click"))) && ($mHtmls->size() > 0)){
             $mHtmls->remove();
         }

        if(($mHtmls = pq(".smile-click")) && ($mHtmls->size() > 0)){
            $mHtmls->removeAttr("onclick");
        }

        if(($mHtmls = pq(".get-click")) && ($mHtmls->size() > 0)){
            foreach($mHtmls as $key=> $mHtml){
                $click =  pq($mHtml)->attr("data-click");
                $html  =  pq($mHtml)->html();
                $html = $click.$html;

                $doc->find(".get-click:eq(".($key).")")->html($html);
            }
        }

        return $doc->htmlOuter();
    }

    /**
     * 获取节点
     * @param $select
     * @param bool $parent
     * @return bool| mixed
     */
    protected function findFirstElement($selected){
        if($selected->size()>0){
            return $selected->elements[0];
        }
        return false;
    }
}